#include <QtGui>

#include "link.h"
#include "node.h"

Link::Link(Node *fromNode, Node *toNode)
{
    myFromNode = fromNode;
    myToNode = toNode;

    myFromDevice = myToDevice = NULL;

    myFromNode->addLink(this);
    myToNode->addLink(this);

    setFlags(QGraphicsItem::ItemIsSelectable);
    setZValue(-1);

    setColor(Qt::darkRed);
    trackNodes();
}

Link::Link(Device *fromNode, Device *toNode)
{
    myFromDevice = fromNode;
    myToDevice = toNode;

    myFromNode = myToNode = NULL;

    myFromDevice->addLink(this);
    myToDevice->addLink(this);

    setFlags(QGraphicsItem::ItemIsSelectable);
    setZValue(-1);

    setColor(Qt::darkRed);
    trackDevs();
}

Link::~Link()
{
    if (myFromNode != NULL)
    {
        myFromNode->removeLink(this);
        myToNode->removeLink(this);
    }
    else
    {
        myFromDevice->removeLink(this);
        myToDevice->removeLink(this);
    }
}

Node *Link::fromNode() const
{
    return myFromNode;
}

Node *Link::toNode() const
{
    return myToNode;
}

Device *Link::fromDevice() const
{
    return myFromDevice;
}

Device *Link::toDevice() const
{
    return myToDevice;
}

void Link::setColor(const QColor &color)
{
    setPen(QPen(color, 1.0));
}

QColor Link::color() const
{
    return pen().color();
}

void Link::trackNodes()
{
    setLine(QLineF(myFromNode->pos(), myToNode->pos()));
}

void Link::trackDevs()
{
    setPen(QPen(Qt::DashLine));
    setLine(QLineF(myFromDevice->pos(), myToDevice->pos()));
}
